package com.hd.h5.camera;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.qrcode.h5.camera.R;

public class H5CameraActivity extends AppCompatActivity {
    private WebView webview;
    private boolean loadError = false;
    private String loadUrl = "";
    private boolean isFirst = true;
    private TextView tvTitle;
    ImageView close;

    private static final int CAMERA_PERMISSION_REQUEST_CODE = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        Intent intent = getIntent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(CAMERA) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{CAMERA,WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, CAMERA_PERMISSION_REQUEST_CODE);
            }
        }
      //  String url = intent.getStringExtra("url");
        String url = "file:///android_asset/index.html";
        webview = findViewById(R.id.webview);
        tvTitle = findViewById(R.id.tv_title);
        View fr_back = findViewById(R.id.img_back);
        /*
        fr_back.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                finish();
            }
        });*/
        WebSettings webseting = webview.getSettings();
        webseting.setDomStorageEnabled(true);
        webseting.setJavaScriptEnabled(true);
        webseting.setUserAgentString("hundun");
        webview.setVisibility(View.GONE);
        webview.setWebViewClient(new WebViewClient() {
                                     @Override
                                     public void onPageFinished(WebView view, String url) {
                                         super.onPageFinished(view, url);
                                         if (loadError) {
                                             webview.setVisibility(View.GONE);

                                         } else {
                                             webview.setVisibility(View.VISIBLE);
                                         }
                                     }

                                     @Override
                                     public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                                         // webview自己加载URL，让后通知系统不需要HandleURL
                                         /*
                                         if (InterceptRequestHelper.intercept(CommonWebVewActivity.this, request.getUrl())) {
                                             return true;
                                         }*/

                                         if (isFirst) {
                                             if (!TextUtils.isEmpty(request.getUrl().getScheme())) {
                                                 loadUrl = request.getUrl().getScheme();
                                                 isFirst = false;
                                             }
                                         }
                                         view.loadUrl(request.getUrl().toString());
                                         String title = webview.getTitle();
                                         return false;
                                     }

                                     @Override
                                     public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                                         handler.proceed();
                                     }

                                     @Override
                                     public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                                         super.onReceivedError(view, request, error);
                                         if (request.isForMainFrame()) {
                                             loadError = true;
                                         }
                                     }

                                     @Override
                                     public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                                         super.onReceivedError(view, errorCode, description, failingUrl);
                                         loadError = true;
                                     }
                                 }

        );

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                // mViewDataBinding.tvTitle.setText(title);
                String webUrl = view.getUrl();
                if (isFirst) {
                    if (!TextUtils.isEmpty(webUrl)) {
                        loadUrl = webUrl;
                        isFirst = false;
                    }
                }
                if (title != null && !title.startsWith("172.16.25.133")) {
                    tvTitle.setText(title);
                }
            }
        });
        webview.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && canWebGoBack()) {
                        //表示按返回键时的操作
                        webview.goBack();
                        return true;
                    }
                }
                return false;
            }
        });
        webview.loadUrl(url);
        fr_back.setOnClickListener(v -> finish());
    }

    private boolean canWebGoBack() {
        if (TextUtils.isEmpty(loadUrl)) {
            return false;
        }
        String url = webview.getUrl();
        if (url.equals(loadUrl)) {
            return false;
        } else {
            close.setVisibility(View.VISIBLE);
            return true;
        }
    }

    public void onBackPressed() {
        if (canWebGoBack()) {
            webview.goBack();

            return;
        }
        super.onBackPressed();
    }

    protected int getLayoutId() {
        return R.layout.h5_camera_layout;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
